// pages/index/index.js
var list = require('../../data/cet6.js');
const innerAudioContext = wx.createInnerAudioContext()
var count = 2;
Page({
  /**
   * 页面的初始数据
   */
  data: {
    navbar: ['新词', '复习'],
    currentTab: 0,

    // 单词
    content: null,
    // 音标
    pron: null,
    // 词性
    definition: null,
    // 单词列表最多为999
    worldListMax: 999,
    // 词汇数据最多为12346
    vocListMax: 12346,
    Id: 0,
    // 读音src
    audioURL: null,
    // 每天的记忆的单词数量
    day_num: 0,
    // 每天的单词列表
    day_word: [],
    // 每个单词的记忆情况
    word_record: [],
    // 计数
    N: 0,
    num: 0,
    list: list,
    // 单词的翻译是否显示
    showNot: false,
    // 数据库中已经有了数据
    have: 1,
    // 判断是否为第一次进入该页面
    count: 0,
    burenshi: true,
    disabled:false,

    //复习
    // 单词
    content2: null,
    // 音标
    pron2: null,
    // 词性
    definition2: null,
    // 读音src
    audioURL2: null,
    // 记录单词的具体信息
    List: {
      id: '',
      content2: '',
      pron2: '',
      definition2: '',
      audioURL2: '',
      showNot2: '',
      collected: ''
    },
    // 计数器
    count2: 0,
    url: null,
    // 单词的翻译是否显示
    showNot2: false,
    // 单词是否收藏
    collected: false,
    // 记录当前点击的单词
    click_word: null,
    //收藏夹
    collection: [],
    // 单词记忆情况
    record: [],
    // 不认识的个数
    fg: 0,
    // 认识的个数
    re: 0,
  },
  //置顶选择栏
  navbarTap: function (e) {
    this.setData({
      currentTab: e.currentTarget.dataset.idx
    })
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var list2 = require('../../data/cet4.js')
    var list3 = require('../../data/cet6.js')
    var list4 = require('../../data/kaoyan.js')
    var list5 = require('../../data/cet4_import.js')
    var list6 = require('../../data/cet6_import.js')
    var list7 = require('../../data/kaoyan_import.js')

    var checked = wx.getStorageSync("checked")
    console.log(checked);
    switch (checked) {
      case 'cet4':
        this.setData({
          list: list2,
        });
        break;
      case 'cet6':
        this.setData({
          list: list3,
        });
        break;
      case '考研':
        this.setData({
          list: list4,
        });
        break;
      case 'cet4高频':
        this.setData({
          list: list5,
        });
        break;
      case 'cet6高频':
        this.setData({
          list: list6,
        });
        break;
      case '考研高频':
        this.setData({
          list: list7,
        });
        break;
    }

    const word_record = wx.getStorageSync("word_record")
    this.setData({
      // 设置任务数
      day_num: wx.getStorageSync('dayNum'),
      word_record: word_record
    })
    var id = wx.getStorageSync("previous") //从缓存中读取上次Id值
    if ("" === (id)) { //如果Id值为空(首次加载页面)，设Id为0
      id = 0;
      console.log("第一次加载！");
    }
    let that = this;
    // 初始化今日的单词列表
    var daynum = wx.getStorageSync('dayNum');
    // var dayNum=id*1+daynum*1;
    console.log("今日的单词数" + daynum);
    //wx.removeStorageSync("now_num");//删除今天已学数量
    var now_num = wx.getStorageSync('now_num');
    if (now_num == 0 || now_num === '') {
      console.log("设置今日单词");
      that.setData({
        day_word: this.data.list.wordList.slice(id, daynum * 1 + id * 1),
        word_record: this.data.list.wordList.slice(id, daynum * 1 + id * 1)
      })
      wx.setStorageSync("day_word", this.data.day_word) //将今日单词存入缓存
    }

    var n = wx.getStorageSync('now_num'); //载入今天已学数量
    var num = wx.getStorageSync('all_num');
    if ("" === (n) || (num) === "") { //如果n值为空(首次加载页面)，设n为0
      n = 0;
      num = 0;
      console.log("第一次加载！");
    }
    console.log(n);
    var word = this.data.word_record[num]
    that.setData({
      content: word,
      Id: id,
      N: n,
      num: num
    })
    // 初始化单词的记忆情况
    if(this.data.N===0){
      this.setData({
        re:0,
        fg:0,
      })
    }else{
      this.setData({
        re:wx.getStorageSync("re"),
        fg:wx.getStorageSync("fg"),
      })
    }
    // 获取audio的url
    that.getaudiourl()

    //复习--------------------------------------------------------------------------------------------------------------------
    //wx.removeStorageSync("collection")
    var collection = wx.getStorageSync("collection")
    if (collection === '') {
      collection = []
    }
    var array = wx.getStorageSync("day_word")

    var List = that.data.List
    that.setData({
      array: array,
      collection: collection
    })

    // 将今日已学的单词的具体信息记录到数组中
    for (var i = 0; i <= n; i++) {
      this.getaudiourl2();
    }


  },


  // 不认识单词或者觉得模糊时显示单词的翻译
  show: function () {
    this.setData({
      showNot: !this.data.showNot,
      burenshi: false,
      disabled:true
    })
    // 记录不认识的单词个数
    if (this.data.num * 1 + 1 <= this.data.day_num) {
      this.setData({
        fg: this.data.fg * 1 + 1,
      })
    }
    // 将不认识的单词再次加入数组末尾
    this.data.word_record.push(this.data.content)
  },

  // 读取下一个单词
  next: function () {
    let that = this;
    var idn;
    var num;
    that.setData({
      showNot: false,
      disabled:false,
    })
    // 判断是否认识这个单词
    if (this.data.burenshi && that.data.num * 1 + 1 <= that.data.day_num) {
      this.setData({
        re: this.data.re * 1 + 1,
      })
    }
    idn = that.data.Id;
    var n = that.data.N;
    num = that.data.num;
    if (this.data.day_num > n) {
      idn++;
      n++;
    }
    num++;
    var word = this.data.word_record[num]
    console.log("当前ID：" + idn);

    // 判断当前是否是最后一个单词
    var daynum = wx.getStorageSync('dayNum');
    var nmax = this.data.word_record.length;
    var qaq = num;
    if (qaq < nmax) {
      that.setData({
        content: word,
        Id: idn,
        audioURL: null,
        N: n,
        num: num,
        burenshi: true

      })
      // 获取audio的url
      that.getaudiourl();
      // // 将今日已学的单词的具体信息记录到数组中
      this.getaudiourl2();
    } else {
      var id = idn
      that.setData({
        N: n,
        Id: id,
        num: num
      })
      wx.setStorageSync("now_num", daynum) //页面跳转前将当前N存入缓存
      wx.setStorageSync("all_num", nmax)

      wx.setStorageSync("word_record", this.data.word_record)
      wx.navigateTo({
        url: '../logs/logs',
      })
    }

    //this.getData();
  },

  // 获取单词的相关信息
  getaudiourl: function () {
    let that = this;
    wx.request({
      url: 'https://api.shanbay.com/bdc/search/?word=' + this.data.content,
      data: {},
      method: 'GET',
      success: function (res) {
        console.log(res)
        that.setData({
          content: res.data.data.content,
          audioURL: res.data.data.audio,
          pron: '/' + res.data.data.pronunciation + '/',
          definition: res.data.data.definition,
        })
        that.read(); //页面加载时，播放发音
        that.get_sams(res.data.data.conent_id)
      }
    })
  },
  // 单词发声
  read() {
    const innerAudioContext = wx.createInnerAudioContext()
    innerAudioContext.autoplay = true
    innerAudioContext.src = this.data.audioURL
    innerAudioContext.play()
    innerAudioContext.onPlay(() => {})
    innerAudioContext.onError((res) => {
      console.log(res.errMsg)
      console.log(res.errCode)
    })
  },
  //获取例句
  get_sams(id) {
    var that = this
    wx.request({
      url: 'https://api.shanbay.com/bdc/example/?vocabulary_id=' + id,
      data: {},
      method: 'GET',
      success: function (res) {
        console.log(res)
        that.setData({
          defen: [res.data.data[0], res.data.data[5]]
        })
      },
      fail: function () {},
      complete: function () {}
    })
  },

  //复习-----------------------------------------------------------------------------------------------------
  // 获取单词的具体信息同时存入记录的数组List
  getaudiourl2: function (e) {
    let that = this;
    var List = that.data.List
    var id = wx.getStorageSync('dayNum');
    var count = that.data.count2
    var record = 'List[' + count + ']'
    // 判断是否为今日学习的最后一个单词
    if (count != id) {
      var word = that.data.array[count]
      //判断是否已收藏
      var cled = false
      for (var i = 0; i < that.data.collection.length; i++) {
        if (that.data.collection[i] == word) {
          cled = true;
          break;
        }
      }
      wx.request({
        url: 'https://api.shanbay.com/bdc/search/?word=' + word,
        data: {},
        method: 'GET',
        success: function (res) {
          that.setData({
            content2: res.data.data.content,
            audioURL2: res.data.data.audio,
            pron2: '/' + res.data.data.pronunciation + '/',
            definition2: res.data.data.definition,
            [record]: {
              word: res.data.data.content,
              pron2: '/' + res.data.data.pronunciation + '/',
              definition2: res.data.data.definition,
              audioURL2: res.data.data.audio,
              showNot2: true,
              collected: cled,
              id: count * 1 - 1,
            }
          })
        }
      })
      count++;
      that.setData({
        count2: count
      })
    }
  },


  // 单词发声
  read2: function (e) {
    var audiourl = e.currentTarget.id;
    console.log("id=" + audiourl)
    const innerAudioContext = wx.createInnerAudioContext()
    innerAudioContext.autoplay = false;
    innerAudioContext.src = audiourl;
    innerAudioContext.play()
    innerAudioContext.onPlay(() => {})
    innerAudioContext.onError((res) => {
      console.log(res.errMsg)
      console.log(res.errCode)
    })
    var definition = e.currentTarget.id;
    console.log("啊哈" + definition);
    this.setData({
      click_word: definition
    })
  },

  show2: function (e) {
    var id = e.currentTarget.id;
    console.log("呕吼" + id);
    var word = this.data.List
    var a = !this.data.List[id].showNot2
    var chang = 'List[' + id + '].showNot2'
    this.setData({
      [chang]: a
    })
    console.log("啊哈" + this.data.List[id].showNot2)
  },

  collect: function (e) {
    var id = e.currentTarget.id;
    console.log("收藏" + id);
    var word = this.data.List
    var a = this.data.List[id].collected
    var b = !this.data.List[id].collected
    if (a == false && b == true) {
      this.data.collection.push(this.data.array[id])
      console.log();
      wx.setStorageSync("collection", this.data.collection)
      console.log("收藏成功");
    } else {
      for (var i = 0; i < this.data.collection.length; i++) {
        if (this.data.collection[i] == this.data.array[id]) {
          this.data.collection.splice(i, 1)
          wx.setStorageSync("collection", this.data.collection);
          break;
        }
      }
    }
    var chang = 'List[' + id + '].collected'
    this.setData({
      [chang]: b
    })
    console.log("收藏" + this.data.List[id].collected)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.getmessage();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },
  // 日期格式转换函数
  formatDate: function (date) {
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    m = m < 10 ? '0' + m : m;
    var d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    return y + '-' + m + '-' + d;
  },

  getrecord: function () {
    const db = wx.cloud.database();
    // 获取此次用户的openid
    var _openid = wx.getStorageSync("_openid");
    // 获取数据库中用户的应用数据
    db.collection('userData').where({
      _openid: _openid,
    }).get({
      success: res => {
        console.log(res)
        this.setData({
          record: res.data[0].record,

        })
      }
    })

  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    // 记录单词的记忆情况
    var record = []
    var today = new Date()
    record = {
      day: this.formatDate(today),
      re: this.data.re,
      fg: this.data.fg
    }
    var arry = this.data.record.concat(record)
    this.setData({
      record: arry,
    })
    wx.setStorageSync("record", arry)
    const db = wx.cloud.database();
    db.collection('userData').doc(this.data.countID).update({
      data: {
        record: arry,
      },
      success: res => {
        console.log('更新数据成功', res)
      },
      fail: err => {
        icon: 'none',
        wx.showToast({
          title: '更新数据失败',
        })
        console.error('[数据库] [更新记录] 失败：', err)
      }
    })
  },

  // 将缓存中的用户数据记录到数据库
  getData: function () {
    const db = wx.cloud.database();
    db.collection('userData').doc(this.data.countID).update({
      data: {
        username: this.data.username,
        id: this.data.Id,
        checked: this.data.checked,
        day_num: this.data.day_num,
        word_record: this.data.word_record,
        collection: this.data.collection,
        day_word: this.data.day_word,
        now_num: wx.getStorageSync("now_num"),
        all_num: wx.getStorageSync("all_num"),
      },
      success: res => {
        console.log('更新数据成功', res)
      },
      fail: err => {
        icon: 'none',
        wx.showToast({
          title: '更新数据失败',
        })
        console.error('[数据库] [更新记录] 失败：', err)
      }
    })

  },

  getmessage: function () {
    // 获取此次用户的openid
    var _openid = wx.getStorageSync("_openid");
    console.log("成了", _openid);
    const db = wx.cloud.database();
    // 获取数据库中用户的信息
    const cont = db.collection('usermessage');
    cont.where({
      _openid: _openid,
    }).get({
      success: res => {
        var username = res.data[0].username;
        this.setData({
          username: username,
        })
        console.log("用户数据:", this.data.username);
      }
    })

    // 获取数据库中用户的应用数据
    db.collection('userData').where({
      _openid: _openid,
    }).get({
      success: res => {
        console.log("查询返回值", res)
        var _id = res.data[0]._id;
        this.setData({
          countID: _id,
        })
        // console.log("用户数据3:", this.data.username);
      }
    })

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    var num = this.data.Id;
    console.log("==onUnload==");
    wx.setStorageSync("previous", num) //页面卸载时将当前Id存入缓存
    wx.setStorageSync("now_num", this.data.N);
    wx.setStorageSync("all_num", this.data.num);
    wx.setStorageSync("word_record", this.data.word_record)
    wx.setStorageSync("fg",this.data.fg)
    wx.setStorageSync("re",this.data.re)
    this.getData();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

})